package chess;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: CommandAction
 *
 */
 public class CommandAction extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public CommandAction() {
		super();
	}   	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cmd = request.getParameter("cmd");
		String rid = request.getParameter("rid");
		String seat = request.getParameter("seat");
		GameHall gameHall = (GameHall)(ContextHelper.getInstance().get("GameHall"));
		GameRoom room  = gameHall.getRoom(rid);
		
		if("start".equals(cmd)){
			if("A".equals(seat)){
				room.setSeatAready(true);
				if(room.getSeatB()!=null)room.addMSG("B", new ReadyStateMSG("ready",""));
				if(room.isSeatBready())room.setStatus("active");
			}else{
				room.setSeatBready(true);
				if(room.getSeatA()!=null)room.addMSG("A", new ReadyStateMSG("ready",""));
				if(room.isSeatAready())room.setStatus("active");
			}
			
		}else if("recall".equals(cmd)){
			
			
		}else if("giveup".equals(cmd)){
			//room.setStatus("inactive");
			room.setSeatAready(false);
			room.setSeatBready(false);
			room.addMSG("A", new ReadyStateMSG("end",seat));
			room.addMSG("B", new ReadyStateMSG("end",seat));
			
		}else if("turn".equals(cmd)){
			if("A".equals(seat)){
				room.setTurn("B");
			}else{
				room.setTurn("A");
			}
		}else if("step".equals(cmd)){
			String step = request.getParameter("step");
			if("A".equals(seat)){
				room.setTurn("B");
				room.addMSG("B", new ReadyStateMSG("step",step));
			}else{
				room.setTurn("A");
				room.addMSG("A", new ReadyStateMSG("step",step));
			}
			
			
		}
	}   	  	    
}